package com.hgyc.mom.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hgyc.mom.system.entity.SysRoleUser;
import com.hgyc.mom.system.service.SysRoleUserService;
import com.hgyc.mom.system.vo.RoleUserVO;
import com.hgyc.mom.system.mapper.SysRoleUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 系统角色用户信息 服务实现类
 * </p>
 *
 * @author fwj
 * @since 2025-01-16
 */
@Service
public class SysRoleUserServiceImpl extends ServiceImpl<SysRoleUserMapper, SysRoleUser> implements SysRoleUserService {

    @Override
    public void updateRoleUser(RoleUserVO roleUserVO) {
        if (!CollectionUtils.isEmpty(roleUserVO.getUserIds())) {
            roleUserVO.getUserIds().forEach(userId -> {
                SysRoleUser sysRoleUser = this.get(roleUserVO.getRoleId(), userId);
                if (sysRoleUser == null) {
                    SysRoleUser newRoleUser = new SysRoleUser();
                    newRoleUser.setRoleId(roleUserVO.getRoleId());
                    newRoleUser.setUserId(userId);
                    this.save(newRoleUser);
                }
            });
        }
    }

    @Override
    public void removeByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getRoleId, roleId);
        this.remove(queryWrapper);
    }

    @Override
    public void remove(Long roleId, Long userId) {
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getRoleId, roleId)
                .eq(SysRoleUser::getUserId, userId);
        this.remove(queryWrapper);
    }

    @Override
    public void removeBatch(RoleUserVO roleUserVO) {
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getRoleId, roleUserVO.getRoleId())
                .in(SysRoleUser::getUserId, roleUserVO.getUserIds());
        this.remove(queryWrapper);
    }

    private SysRoleUser get(Long roleId, Long userId) {
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getRoleId, roleId)
                .eq(SysRoleUser::getUserId, userId);
        return this.getOne(queryWrapper);
    }
}
